const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  // console.log("------"+n)
  // console.log(n[1])
  return n[1]!=null? n : `0${n}`
}

var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

decodeArrayBuffer = function(input) {
  var bytes = (input.length/4) * 3;
  var ab = new ArrayBuffer(bytes);
  this.decode(input, ab);
  return ab;
},

removePaddingChars= function(input){
  var lkey = _keyStr.indexOf(input.charAt(input.length - 1));
  if(lkey == 64){
    return input.substring(0,input.length - 1);
  }
  return input;
},

encode = function (input) {
  var output = "";
  var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  var i = 0;
  // input = _utf8_encode(input);
  while (i < input.length) {
  chr1 = input.charCodeAt(i++);
  chr2 = input.charCodeAt(i++);
  chr3 = input.charCodeAt(i++);
  enc1 = chr1 >> 2;
  enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  enc4 = chr3 & 63;
    if (isNaN(chr2)) {
      enc3 = enc4 = 64;
    } else if (isNaN(chr3)) {
      enc4 = 64;
    }
    output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
     _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
    }
    return output;
      },

decode= function (input, arrayBuffer) {
  //get last chars to see if are valid
  input = removePaddingChars(input);
  input = removePaddingChars(input);

  var bytes = parseInt((input.length / 4) * 3, 10);
  
  var uarray;
  var chr1, chr2, chr3;
  var enc1, enc2, enc3, enc4;
  var i = 0;
  var j = 0;
  
  if (arrayBuffer)
    uarray = new Uint8Array(arrayBuffer);
  else
    uarray = new Uint8Array(bytes);
  
  input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  
  for (i=0; i<bytes; i+=3) {  
    //get the 3 octects in 4 ascii chars
    enc1 = _keyStr.indexOf(input.charAt(j++));
    enc2 = _keyStr.indexOf(input.charAt(j++));
    enc3 = _keyStr.indexOf(input.charAt(j++));
    enc4 = _keyStr.indexOf(input.charAt(j++));

    chr1 = (enc1 << 2) | (enc2 >> 4);
    chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
    chr3 = ((enc3 & 3) << 6) | enc4;

    uarray[i] = chr1;      
    if (enc3 != 64) uarray[i+1] = chr2;
    if (enc4 != 64) uarray[i+2] = chr3;
  }
  return uarray;  
}


module.exports = {
  formatTime,
  decode,
  encode,
  decodeArrayBuffer,
  getArrayIndex
}
